package com.shaozj.common.log.listener;


import cn.hutool.extra.servlet.JakartaServletUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.shaozj.common.log.event.LoginInforEvent;
import com.shaozj.common.log.event.OperLogEvent;
import com.shaozj.core.utils.RequestUtil;
import com.shaozj.core.utils.ip.AddressUtil;
import com.shaozj.system.api.RemoteLoginInforService;
import com.shaozj.system.model.dto.LoginInforDTO;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
@Component
@RequiredArgsConstructor
public class LogEventListener {

    private final RemoteLoginInforService loginInfoFeign;
    /**
     * 保存系统日志记录
     * @param operLogEvent
     */
    @EventListener
    public void saveOperLog(OperLogEvent operLogEvent) {

    }

    /**
     * 保存系统访问记录
     * @param loginInforEvent
     */
    @EventListener
    public void saveLoginInfor(LoginInforEvent loginInforEvent) {
        HttpServletRequest request = RequestUtil.getRequest();
        final UserAgent userAgent = UserAgentUtil.parse(request.getHeader("User-Agent"));
        final String ip = JakartaServletUtil.getClientIP(request);
        String address = AddressUtil.getRealAddressByIP(ip);
        // 获取客户端操作系统
        String os = userAgent.getOs().getName();
        // 获取客户端浏览器
        String browser = userAgent.getBrowser().getName();

        StringBuilder s = new StringBuilder();
        s.append(getBlock(ip));
        s.append(address);
        s.append(getBlock(loginInforEvent.getUsername()));
        s.append(getBlock(loginInforEvent.getStatus()));
        s.append(getBlock(loginInforEvent.getMessage()));
        // 打印信息到日志
        log.info(s.toString(), loginInforEvent.getArgs());

        LoginInforDTO loginInfor = new LoginInforDTO();
        loginInfor.setUserName(loginInforEvent.getUsername());
        loginInfor.setMsg(loginInforEvent.getMessage());
        loginInfor.setLoginLocation(address);
        loginInfor.setIpaddr(ip);
        loginInfor.setBrowser(browser);
        loginInfor.setOs(os);
        loginInfor.setLoginTime(new Date());
        loginInfor.setStatus(loginInforEvent.getStatus());
        loginInfoFeign.saveLoginInfo(loginInfor);
    }



    private String getBlock(Object msg) {
        if (msg == null) {
            msg = "";
        }
        return "[" + msg + "]";
    }

}
